package com.sysu.simulation;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.sysu.simulation.R;
import com.sysu.simulation.helper.AccountHelper;
import com.sysu.simulation.widget.BottomNavButton;
import com.sysu.simulation.widget.BottomNavFragment;
import com.sysu.simulation.interfaces.OnTabReselectListener;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements BottomNavFragment.OnNavigationReselectListener{

    private BottomNavFragment mBottomNav;
    private long firstPressedTime;
    private List<OnBackPressedListener> backListeners = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AccountHelper.init(this.getApplication());
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        FragmentManager manager = getSupportFragmentManager();
        mBottomNav = ((BottomNavFragment) manager.findFragmentById(R.id.bottom_nav));
        mBottomNav.setup(this, manager, R.id.main_container, this);
    }

    @Override
    public void onReselect(BottomNavButton navButton) {
        Fragment fragment = navButton.getFragment();
        if (fragment != null
                && fragment instanceof OnTabReselectListener) {
            OnTabReselectListener listener = (OnTabReselectListener) fragment;
            listener.onTabReselect();
        }
    }

    public BottomNavFragment getBottomNav() {
        return mBottomNav;
    }

    @Override
    public void onBackPressed() {
        for(OnBackPressedListener l : backListeners) {
            if(l.handleBackPressed()) return;
        }

        long curTime = SystemClock.uptimeMillis();
        if ((curTime - firstPressedTime) < (2 * 1000)) {
            finish();
        } else {
            firstPressedTime = curTime;
            Toast.makeText(this, "再次点击退出程序", Toast.LENGTH_SHORT).show();
        }
    }

    public void addOnBackPressedListener(OnBackPressedListener l) {
        backListeners.add(l);
    }

    public interface OnBackPressedListener {
        boolean handleBackPressed();
    }
}
